package com.tansuo365.test1.controller.kucunstuff;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.kucunbean.PosunDetails;
import com.tansuo365.test1.bean.kucunbean.PosunZong;
import com.tansuo365.test1.service.kucunservice.PosunDetailsService;
import com.tansuo365.test1.service.kucunservice.PosunZongService;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunRiZhiService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:danhao.properties")
@Api(value = "破损单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/posundan")
public class PosunDanController {

    @Autowired
    private PosunZongService posunZongService;
    @Autowired
    private PosunDetailsService posunDetailsService;
    @Autowired
    private WuliaoKucunRiZhiService wuliaoKucunRiZhiService;

    @Value("${danhao.posundan.prefix}")
    private String posundanPrefix;

    /**
     * 获取破损单号
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getPosunNumber")
    public ListenableFuture<String> getBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(posundanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxShengouDanNumber = posunZongService.getTodayMaxPosunDanNumber();
        if (todayMaxShengouDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxShengouDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getPosunDan(PosunZong posunZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (posunZong == null) {
            return null;
        }
        System.out.println("项目名称:" + posunZong.getXiangmumingcheng());
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<PosunZong> posunZongsList = posunZongService.listPosunZong(posunZong);
        PageInfo<PosunZong> pageInfo = new PageInfo<PosunZong>(posunZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * 根据zongzhang总表的id查询对应的子表数据 分页
     *
     * @param page
     * @param rows
     * @return 根据总表id遍历查询详细的物料集合
     */
    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(PosunDetails posunDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (posunDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<PosunDetails> posunDetailsList = posunDetailsService.listPosunDetailsSelective(posunDetails);
        PageInfo<PosunDetails> pageInfo = new PageInfo<PosunDetails>(posunDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    @RequestMapping("/save")
    public Map<String, Object> save(HttpSession session, PosunZong posunZong, @RequestParam("wuliaoPosunDetailsJson") String wuliaoPosunDetailsJson) {
        if (posunZong == null || wuliaoPosunDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<PosunDetails> posunDetailsList = gson.fromJson(wuliaoPosunDetailsJson, new TypeToken<List<PosunDetails>>() {
        }.getType());

        posunZong.setChuangjianren((String) session.getAttribute("truename"));
        //save时,先保存大表,大表返回id后再保存附表
        int insertCode = posunZongService.saveZongAndDetails(posunZong, posunDetailsList);
        if(insertCode>0){
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功.");
            return resultMap;
        }else if(insertCode==0){
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
            return resultMap;
        }else if (insertCode < -99) {
            PosunDetails posunDetails = posunDetailsList.get((-insertCode) - 100);
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存破损物料[" + posunDetails.getMingchengguige() + "]超过现有库存数量,请核对库存数量再进行出库操作.");
            return resultMap;
        }else{
            PosunDetails posunDetails = posunDetailsList.get((-(insertCode) - 1));
            resultMap.put("success",false);
            resultMap.put("errorInfo","保存失败,保存物料["+posunDetails.getMingchengguige()+"]不存在库存中.");
            return resultMap;
        }
    }

    @RequestMapping("/update")
    public Map<String, Object> update(PosunZong posunZong) {
        if (posunZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = posunZongService.updateByPrimaryKeySelective(posunZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

    @RequestMapping("/delete")
    @Transactional
    public Map<String,Object> deleteBatch(@RequestParam("ids[]") Integer[] ids){
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        int posundan = wuliaoKucunRiZhiService.insertAndDeletePosunOrWeixiuShu(ids, "posundan");

        int ziDelCode = 0;
        int code = posunZongService.deleteBatchByPKArr(ids);  //
        if(code>0){
            ziDelCode = posunDetailsService.deleteByZongIdArr(ids); //批量删除到货详细根据ids条目
        }
        if (code > 0 && ziDelCode > 0 && posundan>0) {
            resultMap.put("success", true);
        } else {
            resultMap.put("success", false);
        }
        return resultMap;
    }
    

}
